import 'dart:ui';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../const.dart';
import '../routes.dart';
import '../utils/utils.dart';

class Mine extends StatefulWidget {
  @override
  _MineState createState() => _MineState();
}

class _MineState extends State<Mine> {
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  var appName, packageName, version = '', buildNumber;
  var loadingDialog;
  var _loginName = '', _nickName = '';

  var _signState = Const.UNLOGIN;
  var bur = 1.5;
  var _mySubscription;
  var uuid;
  SharedPreferences preferences;
  var _data = 'qqqqqqq';

  _getSp() async {
    preferences = await SharedPreferences.getInstance();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getSp();
  }

  _buildBindSheetItem() {
    List<Widget> list = List();
    list.add(
      ListTile(
        title: Text(
          '是',
          style: TextStyle(color: Const.gold),
        ),
        onTap: () {
          Navigator.pop(context);
          _unbind();
        },
      ),
    );
    return list;
  }

  _buildExitSheetItem() {
    List<Widget> list = List();
    list.add(
      ListTile(
        title: Text(
          '是',
          style: TextStyle(color: Const.gold),
        ),
        onTap: () {
          Navigator.pop(context);
          preferences.clear();
          var code = Utils.getInstance().checkLogin();
          code.then((onValue) {
            setState(() {
              _signState = onValue;
              _loginName = '';
//              eventBus.fire('unsign');
            });
          });
        },
      ),
    );
    return list;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          GestureDetector(
              onTap: () async {
                Map<PermissionGroup, PermissionStatus> permissions =
                    await PermissionHandler().requestPermissions([PermissionGroup.camera]);
                print(permissions);
                if (permissions[PermissionGroup.camera] == PermissionStatus.granted) {
                  String route = '${Routes.qrScanner}';
                  _data = await Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                  setState(() {

                  });
                }

              },
              child: Icon(
                Icons.scanner,
                color: Const.gold,
              ))
        ],
      ),
      backgroundColor: Colors.transparent,
      key: _scaffoldkey,
      body: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: 260,
            decoration: BoxDecoration(
                image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage('images/user_bg.png'),
            )),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: bur, sigmaY: bur),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 30,
                  ),
//                  GestureDetector(
//                    onTap: () {
//                      if (_signState == Const.UNBIND) {
//                        String route = '${Routes.userBind}';
//                        Routes.router.navigateTo(context, route,
//                            replace: false, transition: TransitionType.fadeIn);
//                      } else if (_signState == Const.UNLOGIN) {
//                        Utils.getInstance().showSnackBar(_scaffoldkey, '请先登录');
//                      }
//                    },
//                    child: FadeInImage.assetNetwork(
//                        placeholder: "images/fujin.png",
//                        height: 100,
//                        width: 100,
//                        fit: BoxFit.fill,
//                        image:
//                            'https://zcjpms.xiaoluxueche.com/app/api/v1/member/download/aca2c9c1ce5440d2adb72cb37ea394a8'),
//                  ),
                  SizedBox(
                    height: 26,
                  ),
                  HeadState(
                    data: _data,
                    userName: _loginName == '' ? _nickName : _loginName,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 5,
          ),
          CardBar(
            onTap: () {
              if (_signState == Const.UNLOGIN) {
                Utils.getInstance().showSnackBar(_scaffoldkey, '请先登录');
              } else {
                String route = '${Routes.changePass}';
                Routes.router.navigateTo(context, route,
                    replace: false, transition: TransitionType.fadeIn);
              }
            },
            icon: Icons.vpn_key,
            title: '修改密码',
          ),
          SizedBox(
            height: 5,
          ),
          CardBar(
            icon: Icons.credit_card,
            title: _signState == Const.BIND ? '解绑' : '绑定',
            onTap: () async {
//
            },
          ),
          SizedBox(
            height: 5,
          ),
          CardBar(
            icon: Icons.get_app,
            title: '版本号: $version',
            onTap: () {
//              if (Platform.isIOS) {
//                Utils.getInstance().updateApp('', false);
//              } else {
//
//                MyDio.getInstance().get(Apis.update,
//                        (data) async {
//                      print(data);
//                      if (data['code'] == 200) {
//                        UpdateBean updateBean=UpdateBean.fromJson(data['data']);
//                        if(updateBean.version!=version){
//                          Utils.getInstance().updateApp('http://192.168.1.132:8081/app-release.apk', false);
//                        }else{
//                          Utils.getInstance().showSnackBar(_scaffoldkey, '已经是最新版本');
//                        }
//                      }
//                    });
//              }
            },
          ),
          SizedBox(
            height: 5,
          ),
          Material(
            color: Const.greybar,
            child: InkWell(
              onTap: () {
                if (_signState != Const.UNLOGIN) {
                  Utils.getInstance()
                      .showBottomSheet(context, '是否退出', _buildExitSheetItem());
                } else {
                  String route = '${Routes.loginMain}';
                  Routes.router.navigateTo(context, route,
                      replace: false, transition: TransitionType.fadeIn);
                }
              },
              child: Container(
                height: 60,
                width: MediaQuery.of(context).size.width,
                child: Center(
                  child: Text(
                    _signState != Const.UNLOGIN ? '退出' : '登录',
                    style: TextStyle(color: Const.gold, fontSize: 18),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /* Future<bool> _onBackPressed() {
    return showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('确定退出吗?'),
              elevation: 10,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5)),
              actions: <Widget>[
                FlatButton(
                  child: Text('取消'),
                  onPressed: () => Navigator.pop(context, false),
                ),
                FlatButton(
                  child: Text('确定'),
                  onPressed: () {
//                    Navigator.pop(context, true);
                    _exit();
                  },
//                  onPressed: () => ,
                ),
              ],
            ));
  }*/

  _unbind() {
    Map data = Map<String, String>();
    data['memberBh'] = preferences.getString(Const.UUID);

//    MyDio.getInstance().post(Apis.unbinding, (data) async {
//      print(data);
//      if (data['resultCode'] == 0) {
//        preferences.setString(Const.PERSON_NUM, '');
//        preferences.setString(Const.AREA_CODE, '');
//        Utils.getInstance().showSnackBar(_scaffoldkey, data['msg']);
//        var code = Utils.getInstance().checkLogin();
//        code.then((onValue) {
//          _signState = onValue;
//          setState(() {});
//        });
//      }
//    }, params: data);
  }
}

class HeadPhoto extends StatelessWidget {
  final imageUrl;

  const HeadPhoto({Key key, this.imageUrl}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return imageUrl != null || imageUrl != ''
        ? Image.network(
            imageUrl,
            height: 100,
            width: 100,
            fit: BoxFit.fill,
          )
        : Image.asset(
            '',
            height: 100,
            width: 100,
            fit: BoxFit.fill,
          );
  }
}

class HeadState extends StatelessWidget {
  final userName;
  final data;

  const HeadState({Key key, this.userName, this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return userName == null || userName == ''
        ? Text(
            data,
            style: TextStyle(fontSize: 20, color: Const.gold),
          )
        : Text(userName, style: TextStyle(fontSize: 20, color: Const.gold));
  }
}

class CardBar extends StatelessWidget {
  final icon;
  final title;
  final onTap;

  const CardBar({Key key, this.icon, this.title, this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Const.greybar,
      child: InkWell(
        onTap: onTap,
        child: SizedBox(
          height: 60,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Icon(
                  icon,
                  color: Const.gold,
                  size: 26,
                ),
                SizedBox(
                  width: 16,
                ),
                Text(
                  title,
                  style: TextStyle(color: Const.gold, fontSize: 16),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class LoginButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      width: 100,
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(color: Const.gold, width: 2),
        borderRadius: BorderRadius.circular(16), // 也可控件一边圆角大小
      ),
      child: Center(
          child: Text(
        '点击登录',
        style: TextStyle(color: Const.gold, fontSize: 16),
      )),
    );
  }
}

class BindButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      width: 100,
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(color: Const.gold, width: 2),
        borderRadius: BorderRadius.circular(16), // 也可控件一边圆角大小
      ),
      child: Center(
          child: Text(
        '点击绑定',
        style: TextStyle(color: Const.gold, fontSize: 16),
      )),
    );
  }
}
